import {
  Checkbox,
  DatePicker,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Select,
} from "antd";
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { apiModifyNovel, apiNovelTagAll } from "~/api";
import { apiUserAuthorAll } from "~/api/author";
import { DictType } from "~/common/enum/dict.enum";
import Title from "~/components/ui/title";
import { useDictsMap } from "~/contexts/dict";
import type { IAuthor } from "~/types/manage/content/author";
import type { INovelTag } from "~/types/manage/content/config";

import type { INovel } from "~/types/manage/content/novel";
import { dictToOption } from "~/utils/ui.util";

interface Props {
  visible: boolean;
  record?: INovel | null;
  onCancel?: () => void;
  onOk?: () => void;
}

export default function NovelModal(props: Props) {
  const [form] = Form.useForm<Partial<INovel>>();
  const [authorList, setAuthorList] = useState<IAuthor[]>([]);
  const [novelTagList, setNovelTagList] = useState<INovelTag[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const dictsMap = useDictsMap([
    DictType.CONTENT_KIND,
    DictType.CONTENT_VISUAL_ANGLE,
    DictType.CONTENT_LENGTH_TYPE,
    DictType.CONTENT_STATUS,
    DictType.CONTENT_COPYRIGHT,
    DictType.CONTENT_CONTRACT_TYPE,
    DictType.CONTENT_CONTRACT_STATUS,
    DictType.CONTENT_TYPE,
  ]);

  //   const [coverUrl, setCoverUrl] = useState("");
  //   const [coverLoading, setCoverLoading] = useState(false);

  const _handler = {
    onCancel: () => {
      props.onCancel?.();
    },
    onOk: async () => {
      try {
        setIsSubmitting(true);
        message.info("保存中...");
        await form.validateFields();
        const value: INovel = form.getFieldsValue(true);
        value.storageTime = value.storageTimeDayjs?.format("YYYYMMDD") || "";
        delete value.storageTimeDayjs;
        console.log("value", value);
        await apiModifyNovel(value);
        props.onOk?.();
        message.success("保存成功");
      } catch (error: any) {
        message.error({
          content: error.message,
        });
      } finally {
        setIsSubmitting(false);
      }
    },
  };

  const _fetch = {
    init: async () => {
      await _fetch.userAuthorAll();
      await _fetch.novelTagAll();
    },
    userAuthorAll: async () => {
      try {
        const resp = await apiUserAuthorAll();
        setAuthorList(resp);
      } catch (error: any) {
        message.error({
          content: error.message,
        });
      }
    },
    novelTagAll: async () => {
      try {
        const resp = await apiNovelTagAll();
        setNovelTagList(resp);
      } catch (error: any) {
        message.error({
          content: error.message,
        });
      }
    },
  };

  useEffect(() => {
    _fetch.init();
  }, []);

  useEffect(() => {
    if (!props.visible) {
      return;
    }
    setIsSubmitting(false);
    form.resetFields();
    if (props.record) {
      form.setFieldsValue({
        ...props.record,
        storageTimeDayjs: props.record.storageTime
          ? dayjs(props.record.storageTime)
          : dayjs(),
      });
    }
  }, [props.record, props.visible, form]);

  return (
    <Modal
      title={"基本信息"}
      open={props.visible}
      onCancel={_handler.onCancel}
      onOk={_handler.onOk}
      maskClosable={false}
      width={1200}
    >
      <Form
        form={form}
        className="rp-[.ant-form-item]:!mb-0"
        initialValues={{
          source: dictsMap.CONTENT_COPYRIGHT?.[0]?.code || "",
          kind: dictsMap.CONTENT_KIND?.[0]?.code || "",
          lengthType: dictsMap.CONTENT_LENGTH_TYPE?.[0]?.code || "",
          contentType: dictsMap.CONTENT_TYPE?.[0]?.code || "",
          visualAngle: dictsMap.CONTENT_VISUAL_ANGLE?.[0]?.code || "",
          status: dictsMap.CONTENT_STATUS?.[0]?.code || "",
          totalWords: 0,
          chargeWords: 0,
          totalChapters: 0,
          chargeChapters: 0,
          storageTimeDayjs: dayjs(),
          contractType: dictsMap.CONTENT_CONTRACT_TYPE?.[1]?.code || "",
          contractStatus: dictsMap.CONTENT_CONTRACT_STATUS?.[0]?.code || "",
          unitPrice: 0,
          totalPrice: 0,
        }}
      >
        <Title title="作品基本信息" />
        <div className="my-2 grid grid-cols-3 gap-4 rounded p-4">
          <Form.Item label="编号" name="serialNo">
            <Input disabled />
          </Form.Item>
          <Form.Item label="原编号" name="originSerialNo">
            <Input placeholder="原编号，不输入则为空" allowClear />
          </Form.Item>
          <Form.Item
            label="作者"
            name="userAuthorId"
            className="flex-1"
            rules={[
              {
                required: true,
                message: "作者不可为空",
              },
            ]}
          >
            <Select
              className="!w-full"
              allowClear
              options={authorList.map((item) => ({
                label: (
                  <div className="flex flex-row">
                    <span>{item.penName}</span>
                    <span className="text-gray-400">
                      （{item.email || "--"}）
                    </span>
                  </div>
                ),
                value: item.id,
                record: item,
              }))}
              onSelect={(value, option) => {
                console.log(value, option);
                if (value && option.record) {
                  form.setFieldValue("userId", option.record.userId);
                  form.setFieldValue("userAuthorId", option.record.id);
                } else {
                  form.setFieldValue("userId", "");
                  form.setFieldValue("userAuthorId", "");
                }
              }}
            />
          </Form.Item>
          <Form.Item
            label="标题"
            name="title"
            className="col-span-2"
            rules={[
              {
                required: true,
                message: "标题不可为空",
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="版权来源" name="source">
            <Select options={dictToOption(dictsMap.CONTENT_COPYRIGHT)} />
          </Form.Item>

          {/* <Form.Item label="封面" name="cover" className="col-span-3">
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
            >
              {coverUrl ? (
                <img src={coverUrl} alt="avatar" style={{ width: "100%" }} />
              ) : (
                <button style={{ border: 0, background: "none" }} type="button">
                  {coverLoading ? <LoaderIcon /> : <PlusIcon />}
                  <div style={{ marginTop: 8 }}>上传封面</div>
                </button>
              )}
            </Upload>
          </Form.Item> */}
          <Form.Item label="简介" name="desc" className="col-span-full row-span-3">
            <Input.TextArea
              autoSize={{ maxRows: 5, minRows: 5 }}
              showCount
              maxLength={500}
            />
          </Form.Item>
        </div>
        <Title title="作品相关附加信息" />
        <div className="my-2 grid grid-cols-5 gap-4 rounded p-4">
          <Form.Item label="男女频" name="kind">
            <Select options={dictToOption(dictsMap.CONTENT_KIND)} />
          </Form.Item>
          <Form.Item label="长短类型" name="lengthType">
            <Select options={dictToOption(dictsMap.CONTENT_LENGTH_TYPE)} />
          </Form.Item>
          <Form.Item label="内容类型" name="contentType">
            <Select options={dictToOption(dictsMap.CONTENT_TYPE)} />
          </Form.Item>
          <Form.Item label="视角" name="visualAngle">
            <Select options={dictToOption(dictsMap.CONTENT_VISUAL_ANGLE)} />
          </Form.Item>
          <div className="flex grid-cols-2 justify-around">
            <Form.Item label="" name="isBomb" valuePropName="checked">
              <Checkbox>爆款</Checkbox>
            </Form.Item>
            <Form.Item label="" name="isFocus" valuePropName="checked">
              <Checkbox>重点文</Checkbox>
            </Form.Item>
          </div>
          <Form.Item label="总字数" name="totalWords">
            <InputNumber precision={0} className="!w-full" min={0} />
          </Form.Item>
          <Form.Item label="收费字数" name="chargeWords">
            <InputNumber precision={0} className="!w-full" min={0} />
          </Form.Item>
          <Form.Item label="总章节" name="totalChapters">
            <InputNumber precision={0} className="!w-full" min={0} />
          </Form.Item>
          <Form.Item label="收费章节" name="chargeChapters">
            <InputNumber precision={0} className="!w-full" min={0} />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select options={dictToOption(dictsMap.CONTENT_STATUS)} />
          </Form.Item>
          <Form.Item label="入库月份" name="storageTimeDayjs">
            <DatePicker className="!w-full" />
          </Form.Item>
          <Form.Item label="标签" name="tags" className="col-span-2">
            <Select
              maxTagCount={10}
              mode="multiple"
              allowClear
              options={novelTagList.map((item) => ({
                label: item.label,
                value: item.id,
              }))}
              optionFilterProp="label"
              filterSort={(optionA, optionB) =>
                (optionA?.label ?? "")
                  .toLowerCase()
                  .localeCompare((optionB?.label ?? "").toLowerCase())
              }
            />
          </Form.Item>
          <Form.Item label="备注" name="remark" className="col-span-full">
            <Input.TextArea
              autoSize={{ maxRows: 3, minRows: 3 }}
              showCount
              maxLength={500}
            />
          </Form.Item>
        </div>
        <Title title="作品合同信息" />
        <div className="my-2 grid grid-cols-4 gap-4 rounded p-4">
          <Form.Item label="合同类型" name="contractType">
            <Select options={dictToOption(dictsMap.CONTENT_CONTRACT_TYPE)} />
          </Form.Item>
          <Form.Item label="单价（元）" name="unitPrice">
            <InputNumber className="!w-full" precision={2} />
          </Form.Item>
          <Form.Item label="总价" name="totalPrice">
            <InputNumber className="!w-full" precision={2} />
          </Form.Item>
          <Form.Item label="合同状态" name="contractStatus">
            <Select options={dictToOption(dictsMap.CONTENT_CONTRACT_STATUS)} />
          </Form.Item>
        </div>
      </Form>
    </Modal>
  );
}
